#include <signal.h>

#include <iostream>
using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <wfrest/HttpServer.h>


//通过构造函数初始化计数器的值 
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig %d is coming\n", num);
    //将计数器的值减1
    waitGroup.done();
}


void test0()
{
    using std::string;
    signal(SIGINT, sighandler);
    using namespace wfrest;
    HttpServer httpserver;

    httpserver.GET("/wfrest/test0", [](const HttpReq*, HttpResp*resp){
        resp->append_output_body("hello, wfrest client");
    });

    httpserver.GET("/wfrest/query", [](const HttpReq* req, HttpResp*resp){
        cout << "username:" << req->query("username") << endl;
        auto queryList = req->query_list();
        for(auto & query: queryList) {
            cout << query.first << ": " << query.second << endl;
        }

        resp->append_output_body("hello, wfrest client1");
    });

    httpserver.POST("/wfrest/body", [](const HttpReq* req, HttpResp* resp){
        string body = req->body();
        cout << "body:" << body << endl;
        resp->append_output_body("hello, wfrest client");
    });

    httpserver.POST("/wfrest/urlencoded", [](const HttpReq* req, HttpResp* resp){
        if(req->content_type() == APPLICATION_URLENCODED) {
            auto formKV = req->form_kv();
            for(auto & elem : formKV) {
                cout << elem.first << ": " << elem.second << endl;
            }
        }
        resp->append_output_body("hello, wfrest client");
    });

    httpserver.POST("/wfrest/formdata", [](const HttpReq* req, HttpResp* resp){
        if(req->content_type() == MULTIPART_FORM_DATA) {
            auto form = req->form();
            for(auto & elem : form) {
                cout << elem.first << ": " << elem.second.first << endl;
                cout << elem.second.second << endl;
            }
        }
        resp->append_output_body("hello, wfrest client");
    });
    if(httpserver.track().start(8888) == 0) {
        //列出当前服务器上部署的服务
        httpserver.list_routes();
        waitGroup.wait();
        httpserver.stop();
    } else {
        printf("HttpServer start failed.\n");
    }
}


int main()
{
    test0();
    printf("exit main\n");
    return 0;
}

